package quantum2.draw;

import quantum2.graph.Graph;
import quantum2.graph.Matrix;
import quantum2.graph.Schedule;
import quantum2.graph.StatResult;
import quantum2.math.Arithmetic;

final class Running {

    private final Schedule schedule;
    private final Thread calcThread;

    private final Graph graph;
    private final int startEdge;

    private boolean running = true;

    private boolean inited = false;

    private Running(MainPanel panel, Arithmetic a, Graph g, Matrix matrix) {
        this.startEdge = panel.getStartEdge();
        this.graph = g;
        this.schedule = new Schedule(graph, a, matrix);
        calcThread = new Thread(new Runnable() {
            public void run() {
                init();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    //
                }
                while (true) {
                    synchronized (schedule) {
                        if (!running)
                            break;
                    }
                    schedule.next();
                }
            }
        });
    }

    static Running getRunning(MainPanel panel) {
        Arithmetic a = Arithmetic.createArithmetic(1e-10);
        Graph graph = panel.getGraph(a);
        if (graph == null)
            return null;
        Matrix matrix = panel.getMatrix();
        if (matrix == null)
            return null;
        return new Running(panel, a, graph, matrix);
    }

    private void init() {
        if (!inited) {
            inited = true;
            graph.firstPhotons(startEdge, true, schedule);
        }
    }

    void start() {
        calcThread.start();
    }

    void stop() {
        synchronized (schedule) {
            running = false;
        }
    }

    StatResult getStat() {
        return schedule.getStat();
    }
}
